package jiang.ThreadPool;

import java.util.concurrent.*;

/**
 * @ClassName TestSingleThreadExecutor
 * @Description: 创建一个单线程化的线程池
 * @Author jiangshitao
 * @Date 2023/1/28
 */
public class TestSingleThreadExecutor {

    /**
     * 创建只有一个线程的线程池测试
     * 该方法无参数，所有任务都保存队列LinkedBlockingQueue中，核心线程数为1，线程空闲时间为0
     * 等待唯一的单线程来执行任务，并保证所有任务按照指定顺序(FIFO或优先级)执行
     */
    public void singleThreadPoolTest() {
        // 创建仅有单个线程的线程池
        ExecutorService executorService = Executors.newSingleThreadExecutor(new TestThreadPoolFactory("singleThreadPool"));
        for (int i = 0; i < 10; i++) {
            executorService.submit(() -> {
                        System.out.println(Thread.currentThread().getName());
                    }
            );
        }
    }

    public static void main(String[] args) {
        TestSingleThreadExecutor testSingleThreadExecutor = new TestSingleThreadExecutor();
        long startTime = System.currentTimeMillis();
        testSingleThreadExecutor.singleThreadPoolTest();
        long endTime = System.currentTimeMillis();
        System.out.println("共耗时：" + (endTime-startTime) + "ms");
    }
}
